package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 预约
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 添加预约
     * @param order
     * @return
     */
    @Override
    @Transactional//多表
    public Order add(Order order) {
        log.info("[预约]data:{}", order);

        //查看预约设置信息(根据预约时间查询)
        OrderSetting orderSetting = orderSettingDao.selectByOrderDate(order.getOrderDate());
        if (null == orderSetting) {
            //不存在，不能预约
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        } else if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            //存在,但是预约满了
            throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
        }

        //查询是否有重重复预约（同一个人同一时间同一套餐）
        long orderCount = orderDao.countByMemberAndDateAndSetMeal(order.getMemberId(), order.getOrderDate(), order.getSetmealId());
        if (orderCount > 0) {
            //有重复预约
            throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
        }

        //插入数据
        orderDao.insert(order);

        //修改预约设置（修改已经预约数+1）
        orderSettingDao.updateReservationsById(orderSetting.getId(), orderSetting.getReservations()+1);


        Order selectByIdOrder = orderDao.selectById(order.getId());
        return selectByIdOrder;
    }

    @Override
    public Order findById(Integer id) {
        return orderDao.selectById(id);
    }
}
